package cz.najman.emdroid.ui;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.TextView;

import com.markupartist.android.widget.ActionBar;

import cz.najman.emdroid.R;
import cz.najman.emdroid.helper.EventHelper;
import cz.najman.emdroid.helper.RegistrationStateHelper;
import cz.najman.emdroid.listener.ActionBarOnDataUpdatedListener;
import cz.najman.emdroid.listener.OnDataUpdatedListener;
import cz.najman.emdroid.mappings.Event;
import cz.najman.emdroid.mappings.RegistrationState;

/**
 * @author  Lukáš Najman
 */
public class RegisteredEventsActivity extends ActionBarActivity {
	private static final String TAG = "activity";
		
	private Context mContext;	
	private EMDroidApplication mApplication;
	
	private EventHelper mEventHelper;
	private RegistrationStateHelper mRegistrationStateHelper;

	private ListView mList;
	private SimpleCursorAdapter mAdapter;
	private Cursor mCursor;

	private OnDataUpdatedListener mCustomListener;	
	
	private int mUserId;
	private int mAction;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Setup the GUI */
		setContentView(R.layout.activity_list_with_actionbar);
		mList = (ListView) findViewById(R.id.lvList);
		setActionBarTitle(R.string.app_name);
		setActionBarHomeAction( new Intent(this, HomeActivity.class) );
		
		/* Get needed references */
		mApplication = (EMDroidApplication) getApplication();
		mEventHelper = mApplication.getEventHelper();
		mRegistrationStateHelper = mApplication.getRegistrationStateHelper();

		/* Initialize activity variables */
		mContext = this;		
		mCustomListener = new EMDroidActivityListener(mActionBar);
	}
	
	@Override
	protected void onStart() {
		
		Intent startIntent = getIntent();
		mUserId = startIntent.getIntExtra("userId", -1);
		mAction = startIntent.getIntExtra("action", -1);
		super.onStart();
		
		setupList();
	}

	@Override
	protected void onResume() {		
		mEventHelper.registerListener(Event.class.getCanonicalName(), mCustomListener);
		mRegistrationStateHelper.registerListener(RegistrationState.class.getCanonicalName(), mCustomListener);
		
		if(mUserId != -1){
			mEventHelper.retrieveUsersRegisteredEvents(mUserId);			
			mRegistrationStateHelper.retrieveUsersRegistartionStates(mUserId);
		}		
		
		super.onResume();
	}

	@Override
	protected void onPause() {
		mEventHelper.unregisterListener(Event.class.getCanonicalName());
		mRegistrationStateHelper.unregisterListener(RegistrationState.class.getCanonicalName());
		super.onPause();
	}
	
	private void setupList(){		
		mCursor = mRegistrationStateHelper.getUsersRegistarationStates(mUserId);
		
		startManagingCursor(mCursor);		
		mAdapter = new SimpleCursorAdapter(RegisteredEventsActivity.this,
				R.layout.list_item_registration_state, mCursor,
				new String[] { Event.EVENT_NAME, RegistrationState.EVENT_ID, RegistrationState.STATE_FLAG, RegistrationState.STATE },
				new int[] { R.id.tvRegStateName, R.id.tvRegStateId, R.id.imgSyncIndicator, R.id.imgRegStateIndicator });
		mAdapter.setViewBinder(REG_STATE_INDICATOR_VIEW_BINDER);
		mList.setAdapter(mAdapter);		
		mList.setOnItemClickListener(listViewOnItemClickListener);
	}

	static final ViewBinder REG_STATE_INDICATOR_VIEW_BINDER = new ViewBinder() {
		
		@Override
		public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
			int stateIndex = cursor.getColumnIndex(RegistrationState.STATE);
			int syncIndex = cursor.getColumnIndex(RegistrationState.STATE_FLAG);
			
			if(columnIndex == stateIndex){
				
				ImageView image = (ImageView) view;
				int state = cursor.getInt(columnIndex);
				if(state == 1){
					image.setBackgroundResource(R.color.reg_state_registered);					
				} else if(state == 2){
					image.setBackgroundResource(R.color.reg_state_payed);					
				} else if((state == 3) || (state == 4)){
					image.setBackgroundResource(R.color.reg_state_canceled);					
				}				
				return true;
				
			} else if (columnIndex == syncIndex) {
				
				ImageView image = (ImageView) view;
				int state = cursor.getInt(columnIndex);
				if(state == RegistrationState.STATE_POSTING){
					image.setVisibility(View.VISIBLE);			
				} else {
					image.setVisibility(View.GONE);		
				}
				return true;
				
			} else {
				return false;
			}
		}
	};
	
	public class EMDroidActivityListener extends ActionBarOnDataUpdatedListener {

		public EMDroidActivityListener(ActionBar actionBar) {
			super(actionBar);
		}
		
		@Override
		protected void onFinished(Class objectClass) {	
			
			if(objectClass == RegistrationState.class){
				mCursor.requery();
			}
			
			super.onFinished(objectClass);
		}	
		
	}
	
	final OnItemClickListener listViewOnItemClickListener = new OnItemClickListener() {
		
		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
			LinearLayout view = (LinearLayout) v;
			TextView tv = (TextView) view.getChildAt(view.getChildCount()-1);
			int eventId = Integer.valueOf(tv.getText().toString());
			
			Intent intent = new Intent(mContext, EventDetailsActivity.class);
			intent.putExtra("eventId", eventId);
			intent.putExtra("userId", mUserId);
			intent.putExtra(EventDetailsActivity.ACTION_TYPE, EventDetailsActivity.SHOW_EVENT_WITH_REGISTARTION_STATE);
			startActivity(intent);
			
		}
	}; 

}